// @ts-ignore
import OSS from 'ali-oss'
import {env} from "@/utils/env";


const client = () => {
    return new OSS({
        region: env.VITE_APP_OSS_REGION,
        accessKeyId: env.VITE_APP_OSS_ACCESS_KEY_ID,
        accessKeySecret: env.VITE_APP_OSS_ACCESS_SECRET,
        bucket: env.VITE_APP_OSS_BUCKET
    })
}


const put = (params: { file_name: string; file: File, path: string }) => {
    let fileName = params.path +"/"+ params.file_name;
    let headers = {
        'x-oss-object-acl': 'public-read',
        'Content-Type': getContentType(params.file_name),
        'Content-Disposition': 'inline; filename='+  encodeURIComponent(fileName),
    }
    return  client().put
    (
        env.VITE_APP_OSS_DIR+"/" + fileName,
        params.file,
        {headers}
    );
}

const del = (params: { key: string}) => {
    return client().delete(env.VITE_APP_OSS_DIR + "/" + params.key);
}

const preUrl = () => {
    return  "https://" + env.VITE_APP_OSS_BUCKET + "." + env.VITE_APP_OSS_ENDPOINT + "/" + env.VITE_APP_OSS_DIR + "/";
}


function getContentType(filenameExtension: string){
    if (filenameExtension === ("bmp")) {
        return "image/bmp";
    }
    if (filenameExtension === ("gif")) {
        return "image/gif";
    }
    if (filenameExtension === ("jpeg") || filenameExtension === ("jpg") || filenameExtension === ("png")) {
        return "image/jpg";
    }
    if (filenameExtension === ("html")) {
        return "text/html";
    }
    if (filenameExtension === ("txt")) {
        return "text/plain";
    }
    if (filenameExtension === ("vsd")) {
        return "application/vnd.visio";
    }
    if (filenameExtension === ("pptx") || filenameExtension === ("ppt")) {
        return "application/vnd.ms-powerpoint";
    }
    if (filenameExtension === ("docx") || filenameExtension === ("doc")) {
        return "application/msword";
    }
    if (filenameExtension === ("xml")) {
        return "text/xml";
    }
    return "image/jpg";
}

export {
    put,
    preUrl,
    del
}